package breeze.pixel.weather.main_view.presenter;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Icon;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.view.Display;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;

import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Range;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.view.QWeather;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import breeze.pixel.weather.BaseView;
import breeze.pixel.weather.R;
import breeze.pixel.weather.adapter.AppWeatherManager;
import breeze.pixel.weather.adapter.IAppWeatherHelper;
import breeze.pixel.weather.adapter.weather.AirNowAdapter;
import breeze.pixel.weather.adapter.weather.HourlyAdapter;
import breeze.pixel.weather.adapter.weather.IndicesAdapter;
import breeze.pixel.weather.adapter.weather.MoonAdapter;
import breeze.pixel.weather.adapter.weather.WeatherNowAdapter;
import breeze.pixel.weather.adapter.weather.WarnAdapter;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;
import breeze.pixel.weather.apps_util.utils.appsettings.SettingsStaticData;
import breeze.pixel.weather.apps_util.views.mtextview.MTextView;
import breeze.pixel.weather.earthquake.view.EarthquakeActivity;
import breeze.pixel.weather.main_view.model.HeWeatherErrorCode;
import breeze.pixel.weather.main_view.view.MainView;
import breeze.pixel.weather.moretool.panelmode.view.PanelModeView;
import breeze.pixel.weather.typhoon.TyphoonInfoActivity;
import brz.breeze.app_utils.BAppUtils;
import brz.breeze.tool_utils.Blog;
import brz.breeze.web_utils.BWebUtils;

public class MainViewPresenter implements IMainViewPresenter {

    /**
     * @param cityID 城市id
     */
    @Override
    public void getCityInfo(String cityID) {
        QWeather.getGeoCityLookup(mContext, cityID, Range.CN, 1, Lang.ZH_HANS, new QWeather.OnResultGeoListener() {
            @Override
            public void onError(Throwable throwable) {
                Blog.e(TAG, "获取城市数据失败：" + throwable.toString());
            }

            @Override
            public void onSuccess(GeoBean geoBean) {
                if (Code.OK == geoBean.getCode()) {
                    view.setCityDataInfo(geoBean);
                } else {
                    view.toast("获取城市信息失败：" + geoBean.getCode());
                    Blog.e(TAG, "获取城市信息失败：" + HeWeatherErrorCode.getError(String.valueOf(geoBean.getCode())));
                }
            }
        });
    }

    /**
     * @param cityID 城市id
     */
    @Override
    public void getAirQuality(String cityID) {
        helper.getAirQuality(cityID, new IAppWeatherHelper.AirQualityResponse() {
            @Override
            public void success(AirNowAdapter data) {
                view.setAirNowData(data);
            }

            @Override
            public void fail(String err) {

            }
        });
    }

    @Override
    public void getLifeStyle(String cityId) {
        helper.getIndices(cityId, new IAppWeatherHelper.IndicesResponse() {
            @Override
            public void success(IndicesAdapter data) {
                view.setLifeStyleData(data);
            }

            @Override
            public void fail(String err) {

            }
        });
    }

    @Override
    public void getWeatherWarning(String cityId) {
        helper.getWeatherWarn(cityId, new IAppWeatherHelper.WeatherWarnResponse() {
            @Override
            public void success(WarnAdapter data) {
                view.setWeatherWarning(data);
            }

            @Override
            public void fail(String err) {

            }
        });
    }

    @Override
    public void getHourlyWeather(String cityId) {
        helper.getHourlyWeather(cityId, new IAppWeatherHelper.HourlyWeatherResponse() {
            @Override
            public void success(HourlyAdapter data) {
                view.setHourlyWeatherData(data);
            }

            @Override
            public void fail(String err) {

            }
        });
    }

    @Override
    public void setBingPic(ImageView imageView) {
        BaseView.getExec().execute(() -> {
            Bitmap bitmap = AppToolUtil.getBingPic(mContext);
            imageView.post(() -> imageView.setImageBitmap(bitmap));
        });
    }

    private LocationManager manager;
    private LocationListener listener;

    @Override
    public void getCityInfoByLocation() {
        //定位
        if (ActivityCompat.checkSelfPermission(view.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            getCityInfo(view.sets.getDefaultCityCode());
            return;
        }
        Location lastLocation = getLastLocation();
        if (lastLocation != null) {
            getLocation(lastLocation);
        } else {
            getCityInfo(view.sets.getDefaultCityCode());
        }
    }

    private Location getLastLocation() {
        Context context = view.getApplicationContext();
        manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = manager.getProviders(true);
        Location location = null;
        for (String str : providers) {
            @SuppressLint("MissingPermission") Location lastKnownLocation = manager.getLastKnownLocation(str);
            if (lastKnownLocation == null) {
                continue;
            }
            if (location == null || lastKnownLocation.getAccuracy() < location.getAccuracy()) {
                location = lastKnownLocation;
            }
        }
        return location;
    }

    @Override
    public void getLocation(Location location) {
        if (location != null) {
            double latitude = location.getLatitude();//经度
            double longitude = location.getLongitude();//纬度
            String data = longitude + "," + latitude;
            getCityInfo(data);
            if (manager != null) {
                manager = null;
            }
            if (listener != null) {
                listener = null;
            }
        } else {
            view.toast("获取定位失败");
            getCityInfo(view.sets.getDefaultCityCode());
        }
    }

    @Override
    public boolean checkNotificationIsEnabled() {
        boolean isOpend;
        try {
            isOpend = NotificationManagerCompat.from(view).areNotificationsEnabled();
        } catch (Exception exception) {
            isOpend = false;
        }
        return isOpend;
    }

    @Override
    public void getMoonInfo(String cityID) {
        @SuppressLint("SimpleDateFormat") String date = new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
        helper.getMoonInfo(cityID, new IAppWeatherHelper.MoonInfoResponse() {
            @Override
            public void success(MoonAdapter data) {
                view.setMoonInfo(data);
            }

            @Override
            public void fail(String err) {

            }
        });
    }

    @Override
    public void getAnnouncement(AppSettings settings) {
        BAppUtils.execute(() -> {
            try {
                String webData = BWebUtils.getWebData(SettingsStaticData._ANNOTATION_URI, null, null);
                if (!settings.getAnnouncement().equalsIgnoreCase(webData)) {
                    view.showAnnotation(webData);
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        });
    }

    /**
     * @param cityID 城市id
     * @author BREEZE
     */
    @Override
    public void getCurrentWeather(final String cityID) {
        helper.getWeatherNow(cityID, new IAppWeatherHelper.NowWeatherResponse() {
            @Override
            public void success(WeatherNowAdapter data) {
                view.setWeatherNow(data);
            }

            @Override
            public void fail(String err) {

            }
        });
    }

    /**
     * @param img2，侧滑图片
     * @author BREEZE
     * @description 设置主页面背景图片
     */
    @Override
    public void setMainBackground(ImageView img1, ImageView img2) {
        switch (mAppsettings.getBackgroundModeType()) {
            case AppSettings.TYPE_BACKGROUNDMODE_DEFAULT:
                //线程中获取网页
                //判断文件是否存在
                BaseView.getExec().execute(() -> {
                    Bitmap bitmap = AppToolUtil.getBingPic(mContext);
                    img1.post(() -> {
                        img1.setImageBitmap(bitmap);
                        img2.setImageBitmap(bitmap);
                    });
                });
                break;
            case AppSettings.TYPE_BACKGROUNDMODE_CUSTOM:
                try {
                    String img_cus_1 = AppToolUtil.getMainBackgroundPic(view);
                    String img_cus_2 = AppToolUtil.getDrawerBackgroundPic(view);
                    if (new File(img_cus_1).exists()) {
                        img1.setImageBitmap(BitmapFactory.decodeFile(img_cus_1));
                    } else {
                        setBingPic(img1);
                    }
                    if (new File(img_cus_2).exists()) {
                        img2.setImageBitmap(BitmapFactory.decodeFile(img_cus_2));
                    } else {
                        setBingPic(img2);
                    }
                } catch (Exception e) {
                    view.toast("使用壁纸失败" + e.toString());
                    mAppsettings.setBackgroundModeType(AppSettings.TYPE_BACKGROUNDMODE_DEFAULT);
                    setMainBackground(img1, img2);
                }
                break;
            case AppSettings.TYPE_BACKGROUNDMODE_GESTURE:
                break;
        }
    }


    @Override
    public void initToolbarStyle(final MTextView tv, final LinearLayout ll, final ScrollView scroll) {
        ll.setBackgroundColor(Color.argb(0, 0, 0, 0));
        tv.setTextColor(Color.argb(0, 255, 255, 255));
        scroll.getViewTreeObserver().addOnScrollChangedListener(() -> {
            int ScrollY = scroll.getScrollY();
            if (ScrollY <= 0) {
                ll.setBackgroundColor(Color.argb(0, 0, 0, 0));
                tv.setTextColor(Color.argb(0, 255, 255, 255));
            } else if (ScrollY <= 510) {
                ll.setBackgroundColor(Color.argb(ScrollY / 2, 0, 151, 136));
                tv.setTextColor(Color.argb(ScrollY / 2, 255, 255, 255));
            } else {
                ll.setBackgroundColor(Color.argb(255, 0, 151, 136));
                tv.setTextColor(Color.argb(255, 255, 255, 255));
            }
        });
    }

    @Override
    public void initLayoutWidget(ImageView img, LinearLayout ll, LinearLayout ll2) {
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display defaultdisplay = wm.getDefaultDisplay();
        Point p = new Point();
        defaultdisplay.getRealSize(p);
        ViewGroup.LayoutParams vl = ll.getLayoutParams();
        vl.height = p.y;
        img.setLayoutParams(vl);
        ll.setLayoutParams(vl);
        ll2.setLayoutParams(vl);
    }

    /**
     * @author BREEZE
     * @description 桌面长按图标弹出的工具栏
     */
    @Override
    public void initShortCut() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
                ShortcutManager sm = (ShortcutManager) mContext.getSystemService(Context.SHORTCUT_SERVICE);
                List<ShortcutInfo> listinfos = new ArrayList<>();
                //地震信息
                Intent earthquake = new Intent(mContext, EarthquakeActivity.class);
                earthquake.setAction(Intent.ACTION_VIEW);
                ShortcutInfo earthquack_shortcut = new ShortcutInfo.Builder(mContext, "earthquake")
                        .setShortLabel("地震信息")
                        .setLongLabel("地震信息")
                        .setIcon(Icon.createWithResource(mContext, R.mipmap.icon_earthquake))
                        .setIntent(earthquake)
                        .build();
                listinfos.add(earthquack_shortcut);
                //台风信息
                Intent typhoon = new Intent(mContext, TyphoonInfoActivity.class);
                typhoon.setAction(Intent.ACTION_VIEW);
                ShortcutInfo typhoon_shortcut = new ShortcutInfo.Builder(mContext, "typhoon")
                        .setShortLabel("台风信息")
                        .setLongLabel("台风信息")
                        .setIcon(Icon.createWithResource(mContext, R.mipmap.icon_typhoon))
                        .setIntent(typhoon)
                        .build();
                listinfos.add(typhoon_shortcut);
                //面板模式
                Intent panel_mode = new Intent(mContext, PanelModeView.class);
                panel_mode.setAction(Intent.ACTION_VIEW);
                ShortcutInfo panelmode = new ShortcutInfo.Builder(mContext, "panel")
                        .setShortLabel("面板模式")
                        .setLongLabel("面板模式")
                        .setIcon(Icon.createWithResource(mContext, R.mipmap.icon_panel))
                        .setIntent(panel_mode)
                        .build();
                listinfos.add(panelmode);
                sm.setDynamicShortcuts(listinfos);
            } catch (Exception e) {
                Blog.e(TAG, e.toString());
            }
        }
    }

    public static final String TAG = "MainViewPresenter";

    private final Context mContext;

    private final MainView view;

    private final AppSettings mAppsettings;

    private final IAppWeatherHelper helper;

    public MainViewPresenter(MainView view) {
        this.mContext = view.getApplicationContext();
        this.view = view;
        this.mAppsettings = AppSettings.getInstance(mContext);
        this.helper = AppWeatherManager.getHelper();
    }

}
